package cn.edu.nuc.android.oweibo;

import weibo4android.Weibo;
import weibo4android.WeiboException;
import weibo4android.http.AccessToken;
import weibo4android.http.RequestToken;
import android.app.Application;
import cn.edu.nuc.android.oweibo.authorization.OAuthHelper;

public class OWeiboApplication extends Application {

	private OAuthHelper oAuthHelper;
	private RequestToken currentRequestToken;
	private Weibo weibo;

	@Override
	public void onCreate() {
		super.onCreate();
		oAuthHelper = new OAuthHelper(this);
		weibo = new Weibo();
		oAuthHelper.configureOAuth(weibo);
	}

	/**
	 * �ж��û��Ƿ���Ȩ
	 * @return
	 */
	public boolean isAuthorized() {
		return oAuthHelper.hasAccessToken();
	}

	/**
	 * ��ʼ��Ȩ����
	 * @return
	 */
	public String beginAuthorization() {
		try {
			if (null == currentRequestToken) {
				currentRequestToken = weibo.getOAuthRequestToken("weibo4android://OAuthActivity");
			}
			return currentRequestToken.getAuthorizationURL();
		} catch (WeiboException e) {
		      e.printStackTrace();
	    }
		return null;
	}

	/**
	 * Ӧ����Ȩ
	 */
	public void authorized() {
		try {
			AccessToken accessToken = weibo.getOAuthAccessToken(currentRequestToken);
			oAuthHelper.storeAccessToken(accessToken);
		} catch (WeiboException e) {
			e.printStackTrace();
		}
	}

	public boolean authorize(String pin) {
		try {
			AccessToken accessToken = weibo.getOAuthAccessToken(
					currentRequestToken, pin);
			oAuthHelper.storeAccessToken(accessToken);
			return true;
		} catch (WeiboException e) {
			throw new RuntimeException("Unable to authorize user", e);
		}
	}
	
	public Weibo getWeibo() {
		return weibo;
	}

	public RequestToken getCurrentRequestToken() {
		return currentRequestToken;
	}

}
